package com.homework.controller;

import com.homework.dao.AuthCodeMapper;
import com.homework.feign.EmailFeignClient;
import homework.email.Emailservice;
import homework.facade.dto.AuthCode;
import homework.facade.dto.Response;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Calendar;
import java.util.Date;
import java.util.Random;

@RestController
@RequestMapping("/api/code")
public class CodeController {

    @Autowired
    private AuthCodeMapper authCodeMapper;

    @Autowired
    private RestTemplate restTemplate;

//    @Autowired
//    private EmailFeignClient emailFeignClient;
    @Reference(check = false)
    private Emailservice emailservice;
    @RequestMapping("/create/{email}")
    public Boolean createCode(@PathVariable String email){

        // 1： 随机生成6位数字作为验证码，有效时间10分钟
        Random random = new Random();
        int code = random.nextInt(999999);
        if (code <100000) {
            code += 100000;
        }
        Date createTime = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(createTime);
        calendar.add(Calendar.MINUTE,10);
        Date expireTime = calendar.getTime();
        // 2： 存储验证码
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(String.valueOf(code));
        authCode.setCreatetime(createTime);
        authCode.setExpiretime(expireTime);
        authCodeMapper.addAuthCode(authCode);
        // 3:发送邮件

        Response response = emailservice.sendEmail(email, String.valueOf(code));
//        ResponseEntity<Response> forEntity =
//                restTemplate.getForEntity("http://localhost:8082/api/code/email/" + email + "/" + code, Response.class);
//        String responseCode = forEntity.getBody().getCode();
        String responseCode = response.getCode();
        if ("succ".equals(responseCode)) {
            return true;
        }

        return false;
    }

    @RequestMapping("/validate/{email}/{code}")
    public Integer checkAuthCode(@PathVariable String email,@PathVariable String code){
        AuthCode authCode = authCodeMapper.selectAuthCode(email);
        if (ObjectUtils.isEmpty(authCode)) {
            return 1;
        }
        if (authCode.getCode().equals(code) ) {
            Date expiretime = authCode.getExpiretime();
            if (expiretime.after(new Date())) {
                return 0;
            }
        }
        return 1;
    }
}
